"""
FileName：checkout_page.py
Description：
Author：gaojiahui
Time：2025/8/29 18:38
Website：https://gitee.com/gao-jiahui
"""
from selenium.webdriver.common.by import By

from pages.base_page import BasePage


class CheckoutPage(BasePage):
    """结账页面"""
    # 元素定位器
    ADDRESS_BUTTON = (By.LINK_TEXT, "添加收货地址")
    CONSIGNEE_NAME = (By.LINK_TEXT, "请输入收货人姓名")
    AREA_LOCATION = (By.CSS_SELECTOR, "div.app-address")
    AREA_SELECT_BUTTON = (By.CSS_SELECTOR, "a.app-address-area-a")
    DETAIL_ADDRESS = (By.LINK_TEXT, "请输入详细地址")
    PHONE_NUMBER = (By.LINK_TEXT, "请输入手机号")
    CONFIRM_BUTTON = (By.CSS_SELECTOR, "a.layui-layer-btn0")
    ADDRESS = (By.CSS_SELECTOR, "div.ckt-checkbox.info")
    PAY_TYPE = (By.CSS_SELECTOR, "div.ckt-checkbox.pay")
    EXPRESS_TYPE = (By.CSS_SELECTOR, "div.ckt-checkbox.express")
    COUPON_SELECT = (By.CSS_SELECTOR, "div.money-item-discount")
    SHIP_TIME = (By.CSS_SELECTOR, "div.ckt-checkbox.time")
    PLACE_ORDER = (By.CSS_SELECTOR, "a.bill_btn")

    def send_order(self, consignee_name, detail_address, phone_number):
        """提交订单"""
        self.handle_shipping_address(consignee_name, detail_address, phone_number)
        self.select_pay_type()
        self.select_express_type()
        self.select_coupon()
        self.select_ship_time()
        self.place_order()
        return self

    # 检查是否有收货地址
    def handle_shipping_address(self, consignee_name, detail_address, phone_number):
        """处理收货地址"""
        if self.is_element_present(self.ADDRESS):
            self.click(self.ADDRESS)
        else:
            self.click(self.ADDRESS_BUTTON)
            self.click(self.CONSIGNEE_NAME)
            self.send_keys(self.CONSIGNEE_NAME, consignee_name)
            self.click(self.AREA_LOCATION)
            for _ in range(4):
                self.click(self.AREA_SELECT_BUTTON)
            self.click(self.DETAIL_ADDRESS)
            self.send_keys(self.DETAIL_ADDRESS, detail_address)
            self.click(self.PHONE_NUMBER)
            self.send_keys(self.PHONE_NUMBER, phone_number)
            self.click(self.CONFIRM_BUTTON)
        return self

    # 选择支付方式
    def select_pay_type(self):
        """选择支付方式"""
        self.click(self.PAY_TYPE)
        return self

    # 选择配送方式
    def select_express_type(self):
        """选择配送方式"""
        self.click(self.EXPRESS_TYPE)
        return self

    # 选择优惠券
    def select_coupon(self):
        """选择优惠券"""
        coupon_list = self.find_elements(self.COUPON_SELECT)
        if coupon_list:
            self.click(coupon_list[-1])
        return self

    # 选择配送时间
    def select_ship_time(self):
        """选择配送时间"""
        self.click(self.SHIP_TIME)
        return self

    # 点击下单
    def place_order(self):
        """点击下单"""
        self.click(self.PLACE_ORDER)
        # 点击之后会跳转到收银台页面
        from pages.cashier_page import CashierPage
        return CashierPage(self.driver)
